package com.centit.framework.ip.agentofd.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.centit.framework.common.*;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.core.controller.BaseController;
import com.centit.framework.core.dao.CodeBook;
import com.centit.framework.ip.agentofd.service.OldNewfileinfoManager;
//import com.centit.framework.ip.always.service.AlwaysModelManager;
import com.centit.framework.ip.businessdata.po.MessageInfo;
import com.centit.framework.ip.businessdata.po.TodoItem;
import com.centit.framework.ip.businessdata.service.MessageInfoManager;
import com.centit.framework.ip.businessdata.service.TodoItemManager;
import com.centit.framework.ip.templateFile.service.TemplateFileManager;
import com.centit.framework.ip.util.ClientRequestUtil;
import com.centit.framework.ip.util.layuiResultUtil;
import com.centit.framework.model.adapter.PlatformEnvironment;
import com.centit.framework.model.basedata.IDataDictionary;
import com.centit.framework.model.basedata.IOptInfo;
import com.centit.framework.model.basedata.IRoleInfo;
import com.centit.framework.model.basedata.IUserUnit;
import com.centit.framework.security.model.CentitPasswordEncoder;
import com.centit.framework.security.model.CentitUserDetails;
import com.centit.framework.system.controller.MainFrameController;
import com.centit.framework.system.po.OptInfo;
import com.centit.framework.system.po.UserInfo;
import com.centit.framework.system.service.OptInfoManager;
import com.centit.framework.system.service.SysUserManager;
import com.centit.support.algorithm.UuidOpt;
import com.centit.support.database.utils.PageDesc;
import com.centit.support.database.utils.QueryAndNamedParams;
import com.centit.support.database.utils.QueryUtils;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: 皇甫壮
 * @Date: 2018-6-12 14:58
 * @Description:
 */
@Controller
@RequestMapping("/layui")
public class LayuiMainController extends BaseController {
	public static final String ENTRANCE_TYPE = "ENTRANCE_TYPE";
	public static final String NORMAL_LOGIN = "NORMAL";
	public static final String DEPLOY_LOGIN = "DEPLOY";
	public static final String LOGIN_AUTH_ERROR_MSG = "LOGIN_ERROR_MSG";
	private static String optId = "mainframe";
	@Value("${app.menu.topoptid:}")
	private String topOptId;
	@Value("${login.cas.casHome:}")
	private String casHome ;
	@Value("${login.cas.localHome:}")
	private String localHome ;
	@Resource
	protected PlatformEnvironment platformEnvironment;
	@Resource
	private TodoItemManager todoItemMag;
	@Resource
	private MessageInfoManager messageInfoMag;
	@Resource
	private SysUserManager sysUserManager;
	@Resource
	private CentitPasswordEncoder passwordEncoder;
    @Resource
	private TemplateFileManager templateFileManager;
//    @Resource
//	private AlwaysModelManager alwaysModelManager;
    @Resource
	private OldNewfileinfoManager oldNewfileinfoManager;

	/**
	 *
	 * 功能描述: 首页平台跳转主入口
	 *
	 * @param:
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-6-15 8:52
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public void index(HttpServletRequest request, HttpServletResponse response) {
		CentitUserDetails ud = WebOptUtils.getLoginUser(request);
		try {
			if (ud != null && !"admin".equals(ud.getUserInfo().getLoginName())) {
				request.getRequestDispatcher("/modules/dashboard/dashboard.jsp").forward(request, response);
			} else {
				request.getRequestDispatcher("/system/mainframe/index").forward(request, response);
			}
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	   public String logout(HttpSession session) {
	        session.setAttribute(ENTRANCE_TYPE,NORMAL_LOGIN);
	        session.removeAttribute(LOGIN_AUTH_ERROR_MSG);
	        if(true){
	            //return "sys/mainframe/index";
	            session.invalidate(); 
	            return "redirect:"+casHome+"/logout?service="+localHome+"/system/layui/dashWindow";
	        }
	        else {
	            return "redirect:/logout";//j_spring_security_logout
	        }
	    }
	/**
	 *
	 * 功能描述:
	 *
	 * @param: 由于改写了前端，此处判断是否是admin用户，如果不是则跳到我们自定义的前端页面，是
	 *             admin用户的跳入框架自带的easyui前端框架，菜单实操页面
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-6-12 21:04
	 */
	@RequestMapping(value = "/dashWindow", method = RequestMethod.GET)
	public void dashWindow(HttpServletRequest request, HttpServletResponse response) {
		CentitUserDetails ud = WebOptUtils.getLoginUser(request);
		try {
			if (ud != null && !"admin".equals(ud.getUserInfo().getLoginName())) {
//				String module = request.getParameter("module");// 模块菜单topid
//				module=StringEscapeUtils.escapeHtml(module);
//				module=StringEscapeUtils.escapeJavaScript(module);
				String detailId=request.getParameter("detailId");
				String openid=request.getParameter("openid");
				detailId=StringEscapeUtils.escapeHtml(detailId);
				detailId=StringEscapeUtils.escapeJavaScript(detailId);
				request.setAttribute("detailId",detailId);
				request.setAttribute("openid",openid);
				/*List<IOptInfo> menus=CodeRepositoryUtil.getOptinfoList("A");*/
				List<OptInfo> menus =(List<OptInfo>) platformEnvironment.listUserMenuOptInfos(ud.getUserCode(),
						false);
				StringBuilder stringBuilder = layuiResultUtil.getStringMenu(menus,new StringBuilder());


                List<IRoleInfo> iRoleInfos=(List<IRoleInfo>)ud.getUserRoles();
                //0070:三证大修全角色
                //0051:三证管理角色
                //0050:大修管理角色
                String userRolePower="normal";
                for(IRoleInfo iRoleInfo:iRoleInfos){

                    if("0070".equals(iRoleInfo.getRoleCode())){
                        userRolePower="allAdmin";
                    }else if("0051".equals(iRoleInfo.getRoleCode())){
                        userRolePower="szAdmin";
                    }else if("0050".equals(iRoleInfo.getRoleCode())){
                        userRolePower="dxAdmin";
                    }

                }
				request.getSession().setAttribute("userRolePower",userRolePower);
				request.setAttribute("menusOwner", stringBuilder.toString());
//				request.setAttribute("module", module);
//				request.setAttribute("homeflag",module.toLowerCase());
				request.getRequestDispatcher("/vue/layuiIndex.jsp").forward(request, response);
			}else if(ud==null){
				request.getRequestDispatcher("/system/mainframe/login").forward(request, response);
			}else{
				request.getRequestDispatcher("/system/mainframe/index").forward(request, response);
			}
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 *
	 * 功能描述:
	 *
	 * @param: 由于改写了前端，此处判断是否是admin用户，如果不是则跳到我们自定义的前端页面，是
	 *             admin用户登录后跳进的页面
	 * @return:
	 * @auther: 纪帅
	 * @date: 2018-6-26
	 */
	@RequestMapping(value = "/dashWindowPlat", method = RequestMethod.GET)
	public void dashWindowPlat(HttpServletRequest request, HttpServletResponse response) {
		CentitUserDetails ud = WebOptUtils.getLoginUser(request);
		try {
			String primaryUnit = "";
			String primaryName = "";
			if (ud != null && !"admin".equals(ud.getUserInfo().getLoginName())) {
				primaryUnit = ud.getUserInfo().getPrimaryUnit();
				primaryName = CodeRepositoryUtil.getUnitName(primaryUnit);
				Date day = new Date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
				SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");

				String currentTime = df.format(day);
				String xq = dateFm.format(day);
				request.setAttribute("primaryName", primaryName);
				request.setAttribute("currentTime", currentTime);
				request.setAttribute("xq", xq);
				request.getRequestDispatcher("/modules/dashboard/dashboardPlat.jsp").forward(request, response);
			} else {
				request.getRequestDispatcher("/system/mainframe/index").forward(request, response);
			}
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 *
	 * 功能描述:
	 *
	 * @param: 首页下面嵌套的数据大页面
	 *             admin用户登录后跳进的页面
	 * @return:
	 * @auther: 纪帅
	 * @date: 2018-6-27
	 */
	@RequestMapping(value = "/dashWindowPlatDownPage", method = RequestMethod.GET)
	public void dashWindowPlatDownPage(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
		try {
			response.setHeader("X-Frame-Options", "SAMEORIGIN");// 解决IFrame拒绝的问题
			String from = request.getParameter("from");
			CentitUserDetails ud=getLoginUser(request);
			// 待办事项列表
			Map<String, Object> filterMapItem = new HashMap<>();
			if(ud!=null) {
				filterMapItem.put("isValid", "T");
				filterMapItem.put(CodeBook.SELF_ORDER_BY, " createTime desc");
				filterMapItem.put("userCode",ud.getUserCode());
				List<TodoItem> itemList = todoItemMag.listObjects(filterMapItem);
				request.setAttribute("items", itemList);
			}
			if (from != null && !"".equals(from)) {
				request.setAttribute("havePerson", "1");
			} else {
				request.setAttribute("havePerson", "2");
			}
			filterMapItem.clear();
			filterMapItem.put("dataType", "2");
			filterMapItem.put("isValid", "T");
			filterMapItem.put(CodeBook.SELF_ORDER_BY," createTime desc");
			pageDesc.setPageSize(10);
			pageDesc.setPageNo(1);
			JSONArray noticeJson =messageInfoMag.listObjectsAsJson(filterMapItem,pageDesc) ;// 通知公告
			filterMapItem.put("dataType", "3");
			JSONArray trainJson = messageInfoMag.listObjectsAsJson(filterMapItem,pageDesc) ;// 学习心得
			filterMapItem.put("dataType", "4");
			JSONArray pxjcJson = messageInfoMag.listObjectsAsJson(filterMapItem,pageDesc) ;// 培训教材
			filterMapItem.put("dataType", "5");
			JSONArray dynamicJson = messageInfoMag.listObjectsAsJson(filterMapItem,pageDesc) ;// 委内工作动态
			filterMapItem.put("dataType", "6");
			JSONArray summaryJson = messageInfoMag.listObjectsAsJson(filterMapItem,pageDesc) ;// 工作总结
			filterMapItem.clear();
			filterMapItem.put("dataType", "7");
			JSONArray LdJson = messageInfoMag.listObjectsAsJson(filterMapItem,pageDesc) ;// 出国公示
			filterMapItem.put("dataType", "8");
			JSONArray ckzlJson = messageInfoMag.listObjectsAsJson(filterMapItem,pageDesc) ;// 表彰公示
			filterMapItem.put("dataType", "9");
			JSONArray khgsJson = messageInfoMag.listObjectsAsJson(filterMapItem,pageDesc) ;// 考核公示
			filterMapItem.put("dataType", "10");
			JSONArray informationJson = messageInfoMag.listObjectsAsJson(filterMapItem,pageDesc) ;// 经济信息
			request.setAttribute("noticeJson",noticeJson);
			request.setAttribute("trainJson",trainJson);
			request.setAttribute("pxjcJson",pxjcJson);
			request.setAttribute("dynamicJson",dynamicJson);
			request.setAttribute("summaryJson",summaryJson);
			request.setAttribute("LdJson",LdJson);
			request.setAttribute("ckzlJson",ckzlJson);
			request.setAttribute("informationJson",informationJson);
			request.setAttribute("khgsJson",khgsJson);
			String flag=request.getParameter("flag");
			if(StringUtils.isNotBlank(flag)&&"cas".equals(flag)){//cas登录页面展示
				request.getRequestDispatcher("/modules/dashboard/dashboardPlatDownPageCas.jsp").forward(request, response);
			}else{
			request.getRequestDispatcher("/modules/dashboard/dashboardPlatDownPage.jsp").forward(request, response);
			}
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 *
	 * 功能描述:
	 *
	 * @param: 首页下面嵌套的数据大页面
	 *             admin用户登录后跳进的页面
	 * @return:
	 * @auther: 纪帅
	 * @date: 2018-6-27
	 */
	@RequestMapping(value = "/dashWindowPlatLeftPage", method = RequestMethod.GET)
	public void dashWindowPlatLeftPage(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
		try {
			response.setHeader("X-Frame-Options", "SAMEORIGIN");// 解决IFrame拒绝的问题
			// 图片新闻
			Map<String, Object> filterMapItem = new HashMap<>();
			pageDesc.setPageSize(5);
			pageDesc.setPageNo(1);
			String sql=" select rec_id,datatitle,newfileid,url from t_Message_Info where datatype='11' and isvalid='T' and newfileid is not null order by createtime desc";
			QueryAndNamedParams params = QueryUtils.translateQuery(sql, filterMapItem);
			JSONArray jsonArray=todoItemMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),pageDesc);
			request.setAttribute("items", jsonArray);
			request.getRequestDispatcher("/modules/dashboard/dashboardPlatLeftPage.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 跳转修改用户页面
	 * 
	 * 
	 * 
	 * @param response
	 *            {@link HttpServletResponse}
	 * @return {data:{}}
	 */
	@RequestMapping(value = "/goEdit", method = { RequestMethod.GET })
	public void goEdit(HttpServletRequest request, HttpServletResponse response) {
		CentitUserDetails ud = WebOptUtils.getLoginUser(request);
		CentitUserDetails user = platformEnvironment.loadUserDetailsByLoginName(ud.getUsername());
		JsonResultUtils.writeSingleDataJson(user, response);
	}

	/**
	 * 查看用户信息
	 *
	 *
	 *
	 * @param response
	 *            {@link HttpServletResponse}
	 * @return {data:{}}
	 */
	@RequestMapping(value = "/viewUserInfo", method = { RequestMethod.GET })
	public void viewUserInfo(HttpServletRequest request, HttpServletResponse response) {
		CentitUserDetails ud = WebOptUtils.getLoginUser(request);
		CentitUserDetails user = platformEnvironment.loadUserDetailsByLoginName(ud.getUsername());
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/modules/dashboard/viewUser.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 修改用户
	 * 
	 * @param {@link
	 * 			}
	 * @param response
	 *            {@link HttpServletResponse}
	 */
	@RequestMapping(value = "/update", method = { RequestMethod.POST })
	public void update(@Valid UserInfo userInfo, HttpServletRequest request, HttpServletResponse response) {
		String newpassword = request.getParameter("newpassword");
		String message = "操作成功";
		String code = "T";
		if (userInfo != null && StringUtils.isNotBlank(userInfo.getUserCode())) {
			userInfo.setUserName(StringEscapeUtils.escapeHtml(userInfo.getUserName()));//特殊字符过滤
			UserInfo dbuser = sysUserManager.getObjectById(userInfo.getUserCode());
			Boolean enBool = passwordEncoder.isPasswordValid(dbuser.getUserPin(), userInfo.getUserPin(),
					userInfo.getUserCode());
			if (enBool) {
				userInfo.setUserPin(passwordEncoder.encodePassword(newpassword, userInfo.getUserCode()));
				dbuser.copyNotNullProperty(userInfo);
				//copynotnull修改密码被注释掉了，下面手动修改下
				dbuser.setUserPin(userInfo.getUserPin());
				sysUserManager.updateUserInfo(dbuser);
				platformEnvironment.loadUserDetailsByUserCode(userInfo.getUserCode());// 刷新缓存用户信息
			} else {
				message = "原密码不正确";
				code = "F";
			}
		} else {
			message = "当前用户不存在";
			code = "F";
		}
		JSONObject json = new JSONObject();
		json.put("code", code);
		json.put("message", message);
		JsonResultUtils.writeSingleDataJson(json, response);
	}

	/**
	 * 首页菜单
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 */
	@RequestMapping(value = "/menu", method = RequestMethod.GET)
	public void getMenu(HttpServletRequest request, HttpServletResponse response) {
		CentitUserDetails userDetails = super.getLoginUser(request);
		if (userDetails == null) {
			JsonResultUtils.writeHttpErrorMessage(ResponseData.ERROR_USER_NOT_LOGIN, "用户没有登录，请重新登录！", response);
			return;
		}
		Object obj = request.getSession().getAttribute(ENTRANCE_TYPE);
		boolean asAdmin = obj != null && DEPLOY_LOGIN.equals(obj.toString());
		List<? extends IOptInfo> menuFunsByUser = null;
		List<? extends IOptInfo> curr=null;
		String module = request.getParameter("module");
		topOptId=module;
		String currOptid=request.getParameter("detailId");
		if(StringUtils.isNotBlank(currOptid)){
			topOptId=currOptid;
		}
//		if (StringUtils.isNotBlank(topOptId) && !"all".equals(topOptId)) {
			/*menuFunsByUser = platformEnvironment
					.listUserMenuOptInfosUnderSuperOptId(userDetails.getUserInfo().getUserCode(), topOptId, asAdmin);*/
			menuFunsByUser=messageInfoMag.listOptId(userDetails.getUserInfo().getUserCode(), topOptId, asAdmin,module,currOptid);
//		}
		JSONArray menuJson = makeMenuFuncsJson(menuFunsByUser);
		JsonResultUtils.writeSingleDataJson(menuJson, response);
	}

	@RequestMapping(value = "/submenu", method = RequestMethod.GET)
	public void getMenuUnderOptId(@RequestParam(value = "optid", required = false) String optId,
			HttpServletRequest request, HttpServletResponse response) {

		CentitUserDetails userDetails = super.getLoginUser(request);
		if (userDetails == null) {
			JsonResultUtils.writeHttpErrorMessage(ResponseData.ERROR_USER_NOT_LOGIN, "用户没有登录，请重新登录！", response);
			return;
		}
		Object obj = request.getSession().getAttribute(ENTRANCE_TYPE);
		boolean asAdmin = obj != null && DEPLOY_LOGIN.equals(obj.toString());
		List<? extends IOptInfo> menuFunsByUser = platformEnvironment
				.listUserMenuOptInfosUnderSuperOptId(userDetails.getUserInfo().getUserCode(), optId, asAdmin);
		if (menuFunsByUser == null) {
			JsonResultUtils.writeHttpErrorMessage(ResponseData.ERROR_USER_NOT_LOGIN, "用户没有登录,或者没有给用户任何权限，请重新登录！",
					response);
			return;
		}

		JsonResultUtils.writeSingleDataJson(makeMenuFuncsJson(menuFunsByUser), response);
	}

	private JSONArray makeMenuFuncsJson(List<? extends IOptInfo> menuFunsByUser) {
		return ViewDataTransform.makeTreeViewJson(menuFunsByUser,
				ViewDataTransform.createStringHashMap("id", "optId", "pid", "preOptId", "text", "optName", "url",
						"optRoute", "icon", "icon", "children", "children", "isInToolbar", "isInToolbar"
				// "attributes.external","pageType"
				), (jsonObject, obj) -> jsonObject.put("external", !("D".equals(obj.getPageType()))));
	}

	/**
	 * 获取OA领导日程信息
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 */
	@RequestMapping(value = "/getSchedule", method = RequestMethod.GET)
	public void getSchedule(HttpServletRequest request, HttpServletResponse response) {
		CentitUserDetails cud = getLoginUser(request);// 获取登录信息
		String curUserCode = "";
		if(cud!=null){
			curUserCode = cud.getUserCode();
		}
		String userCode = request.getParameter("userCode");
		userCode= StringEscapeUtils.escapeSql(userCode);
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.add("X-Auth-Token", UuidOpt.getUuidAsString32());
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		Map<String, Object> postParameters = new HashMap<String, Object>();
		if ("init".equals(userCode)) {
			userCode = curUserCode;
		}
		if (userCode != null) {
			postParameters.put("userCode", userCode);
		}
		HttpEntity<String> requestEntity = new HttpEntity<String>(JSONObject.toJSONString(postParameters), headers);
		String oaservicepath = CodeRepositoryUtil.getSysConfigValue("oaservicepath");
		JSONArray jsonArr = new JSONArray();
		String result = ClientRequestUtil.getRestTemplate().postForObject(oaservicepath + "/service/out/scheduleApp/ldrcRl",
				requestEntity, String.class);
		if (result != null) {
			JSONObject json = JSONObject.parseObject(result);
			JSONObject jsonData = json.getJSONObject("data");
			jsonArr = jsonData.getJSONArray("objList");
		}
		JsonResultUtils.writeSingleDataJson(jsonArr, response);
	}
	/**
	 * 获取委领导信息，用于首页渲染下拉框
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 */
	@RequestMapping(value = "/getWldList", method = RequestMethod.GET)
	public void getWldList(HttpServletRequest request, HttpServletResponse response) {
		//List<IUserUnit> userUnits= (List<IUserUnit>)CodeRepositoryUtil.listUnitUsers("149");//委领导部门编码
		String sql="select t.user_code,t.user_name,t.user_order from f_userinfo t ,f_userunit t1 where t.user_code=t1.user_code and t1.unit_code=?" +
				" order by to_number(t.user_order) ";
		String[] params=new String[]{"149"};
		JSONArray infos=templateFileManager.getAsJsonBySql(sql,params);
		JsonResultUtils.writeSingleDataJson(infos, response);
	}

	/**
	 * 跳转委领导选择页面
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 */
	@RequestMapping(value = "/toWldPage", method = RequestMethod.GET)
	public void toWldPage(HttpServletRequest request, HttpServletResponse response) {
		String sql="select t.user_code,t.user_name,t.user_order from f_userinfo t ,f_userunit t1 where t.user_code=t1.user_code and t1.unit_code=?" +
				" order by to_number(t.user_order) ";
		String[] params=new String[]{"149"};
		JSONArray infos=templateFileManager.getAsJsonBySql(sql,params);
		request.setAttribute("infos",infos);
		try {
			request.getRequestDispatcher("/modules/dashboard/wldPage.jsp").forward(request,response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取会议信息
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 */
	@RequestMapping(value = "/getMeetList", method = RequestMethod.GET)
	public void getMeetList(HttpServletRequest request, HttpServletResponse response) {
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.add("X-Auth-Token", UuidOpt.getUuidAsString32());
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		Map<String, Object> postParameters = new HashMap<String, Object>();
		String page = request.getParameter("page");
		Integer pageNo = 1;
		Integer pageSize = 6;
		pageNo = StringUtils.isNotEmpty(page) ? Integer.valueOf(page) : pageNo;
		postParameters.put("pageNo",String.valueOf(pageNo));
		postParameters.put("pageSize",String.valueOf(pageSize));
		PageDesc pageDesc=new PageDesc();
		pageDesc.setPageNo(pageNo);
		pageDesc.setPageSize(pageSize);
		HttpEntity<String> requestEntity = new HttpEntity<String>(JSONObject.toJSONString(postParameters), headers);
		String meetservicepath = CodeRepositoryUtil.getSysConfigValue("meetservicepath");
		try {
			String hyListResult = ClientRequestUtil.getRestTemplate().postForObject(meetservicepath+"/service/meet/hyglhyrcApp/getHyrcList",
					requestEntity, String.class);
			JSONObject jsonHy = JSONObject.parseObject(hyListResult);
			JSONArray jsonHyData =jsonHy==null?null:jsonHy.getJSONArray("data");
			if(jsonHy!=null){
				Integer count=(Integer)jsonHy.get("count");
				pageDesc.setTotalRows(count);
			}

			ResponseMapData resData = new ResponseMapData();
			resData.addResponseData(OBJLIST, jsonHyData);
			resData.addResponseData(PAGE_DESC, pageDesc);
			layuiResultUtil.layuiwriteResponseDataAsJson(resData,pageDesc, response);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	/**
	 *
	 * 功能描述: 菜单页根据用户获取常用功能，默认显示排名前8个
	 *
	 * @param:
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-7-28 20:35
	 */
	@RequestMapping(value = "/loadModelsByUsercode", method = RequestMethod.GET)
	public void loadModelsByUsercode(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
//		CentitUserDetails cud = getLoginUser(request);// 获取登录信息
//		Map<String, Object> searchColumn = convertSearchColumn(request);
//		String curUserCode = "";
//		if(cud!=null){
//			curUserCode = cud.getUserCode();
//		}
//		searchColumn.put("dataValidFlag",1);
//		searchColumn.put("usercode",curUserCode);
//		pageDesc.setPageNo(1);
//		pageDesc.setPageSize(8);
//		JSONArray listArr=alwaysModelManager.listObjectsAsJson(searchColumn,pageDesc);
//		JSONArray result=new JSONArray();
//		if(listArr!=null&&listArr.size()>0){
//			JSONObject jsonObject=null;
//			JSONObject dataJson=null;
//			String[] imgurl=null;
//			String imgstr="";
//			for (int i=0;i<listArr.size();i++){
//                 jsonObject=new JSONObject();
//				 dataJson=listArr.getJSONObject(i);
//                 jsonObject.put("name",dataJson.getString("modelname"));
//				 jsonObject.put("code",dataJson.getString("modelcode"));
//				jsonObject.put("modelclass",dataJson.getString("modelclass"));
//				imgstr=dataJson.getString("modelimgurl");
//				 if(StringUtils.isNotBlank(imgstr)){
//				  imgurl=imgstr.split("[.]");
//				  jsonObject.put("imgurl",imgurl[0]);
//				  jsonObject.put("imgType","."+imgurl[1]);
//				 }
//				 result.add(jsonObject);
//			}
//		}
//		JsonResultUtils.writeSingleDataJson(result, response);
	}
    /**
     *
     * 功能描述: 委内收发文统计
     *
     * @param:
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-8-9 15:08
     */
	@RequestMapping(value = "/loadsfwAll", method = RequestMethod.GET)
	public void loadsfwAll(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
		JSONObject json=oldNewfileinfoManager.loadsfwAll();
		JsonResultUtils.writeSingleDataJson(json, response);
	}
	/**
	 *
	 * 功能描述: 委内当天收发文统计
	 *
	 * @param:
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-8-9 16:36
	 */
	@RequestMapping(value = "/sfwCurrDay", method = RequestMethod.GET)
	public void sfwCurrDay(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
		JSONObject json=oldNewfileinfoManager.sfwCurrDay();
		JsonResultUtils.writeSingleDataJson(json, response);
	}
	/**
	 *
	 * 功能描述:会议室top5使用情况
	 *
	 * @param:
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-9-6 16:07
	 */
	@RequestMapping(value = "/getUnitMeetInfo", method = RequestMethod.GET)
	public void getUnitMeetInfo(HttpServletRequest request, HttpServletResponse response) {
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.add("X-Auth-Token", UuidOpt.getUuidAsString32());
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		Map<String, Object> postParameters = new HashMap<String, Object>();
		HttpEntity<String> requestEntity = new HttpEntity<String>(JSONObject.toJSONString(postParameters), headers);
		String meetservicepath = CodeRepositoryUtil.getSysConfigValue("meetservicepath");
		try {
			String hyListResult = ClientRequestUtil.getRestTemplate().getForObject(meetservicepath+"/service/meet/hyglhyrcApp/getHyrcUnitCount",
					String.class,requestEntity);
			JSONObject jsonHy = JSONObject.parseObject(hyListResult);
			JSONArray jsonHyData = jsonHy.getJSONArray("data");
			JsonResultUtils.writeSingleDataJson(jsonHyData, response);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}
	/**
	 *
	 * 功能描述:注册子系统模块用户，之前ajax直接注册的控制不了超时时间，这边放在后台设置超时时间
	 *
	 * @param:
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-8-30 16:59
	 */
	@RequestMapping(value = "/registermodel", method = RequestMethod.GET)
	public void registermodel(HttpServletRequest request, HttpServletResponse response) {
		try {
			String[]urls=request.getParameterValues("urls");
			if(urls!=null&&urls.length>0){
				for (String item:urls){
					URL url=new URL(item);
					HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
					urlConnection.setConnectTimeout(3000);
					urlConnection.setReadTimeout(3000);
					urlConnection.setRequestMethod("GET");
					urlConnection.connect();
					int code=urlConnection.getResponseCode();
					System.out.println(code+"========================");
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		JsonResultUtils.writeSingleDataJson("成功", response);
	}
	/**
	 *
	 * 功能描述: 项目管理地图信息
	 *
	 * @param:
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-9-7 11:04
	 */
	@RequestMapping(value = "/getXmglMap", method = RequestMethod.GET)
	public void getXmglMap(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request);
		String doctrans=CodeRepositoryUtil.getValue("TYPZ","doctrans");
		String sql="select data_value name,to_char(money)money,to_char(numb) value,data_code code" +
				" from f_datadictionary t,(" +
				" select substr(place_code,0,4)||'00' codea,sum(total_money)/10000 money,count(1) numb from "+doctrans+".TZ_APPLY_PROJECT_INFO t where 1=1 [:year|and to_char(apply_date,'yyyy')=:year] group by substr(place_code,0,4)" +
				")t1 " +
				" where t.catalog_code='CITY' and t.data_code=codea  order by numb desc";
		QueryAndNamedParams params = QueryUtils.translateQuery(sql, searchColumn);
		JSONArray jsonArray=messageInfoMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
		JSONObject json=new JSONObject();
		json.put("mapdata",jsonArray);
		if(jsonArray!=null&&jsonArray.size()>0){
			String max=(String)jsonArray.getJSONObject(0).get("value");
			String min=(String)jsonArray.getJSONObject(jsonArray.size()-1).get("value");
			json.put("max",max);
			json.put("min",min);
		}else{
			json.put("max",100);
			json.put("min",0);
		}
		JsonResultUtils.writeSingleDataJson(json, response);
	}
	/**
	 *
	 * 功能描述: 获取申报项目信息
	 *
	 * @param:
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-9-6 16:08
	 */
	@RequestMapping(value = "/getXmglInfo", method = RequestMethod.GET)
	public void getXmglInfo(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request);
		String doctrans=CodeRepositoryUtil.getValue("TYPZ","doctrans");
		String sql="select  valuename text,to_char(numb) max,rownum nu from (" +
				" select INDUSTRY ,numb from(" +
				" select INDUSTRY,count(1)numb from "+doctrans+".TZ_APPLY_PROJECT_INFO t where 1=1 [:year| and to_char(apply_date,'yyyy')=:year]" +
				"[:cityCode| and substr(place_code,0,4)||'00'=:cityCode] group by INDUSTRY) order by numb desc),"+doctrans+".T_HYFL where level4=INDUSTRY  and rownum<6";
		QueryAndNamedParams params = QueryUtils.translateQuery(sql, searchColumn);
		JSONArray jsonArray=messageInfoMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
		sql="select to_char(count(1))numb from "+doctrans+".TZ_APPLY_PROJECT_INFO where 1=1 [:year|and to_char(apply_date,'yyyy')=:year]" +
				"[:cityCode| and substr(place_code,0,4)||'00'=:cityCode]";
		params = QueryUtils.translateQuery(sql, searchColumn);
		JSONArray total=messageInfoMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
        if(jsonArray!=null&&jsonArray.size()>0){
        	String tonub=(String) total.getJSONObject(0).get("numb");
        	for (int i=0;i<jsonArray.size();i++){
				String  numb=(String)jsonArray.getJSONObject(i).get("max");
				BigDecimal big=new BigDecimal(Double.valueOf(numb)/Double.valueOf(tonub)*100);
				jsonArray.getJSONObject(i).put("zb", big.setScale(2,BigDecimal.ROUND_HALF_UP));
			}
		}
		JsonResultUtils.writeSingleDataJson(jsonArray, response);
	}
	/**
	 *
	 * 功能描述: 项目总数以及资金
	 *
	 * @param:
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-10-28 23:27
	 */
	@RequestMapping(value = "/getxmMoney", method = RequestMethod.GET)
	public void getxmMoney(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request);
		String doctrans=CodeRepositoryUtil.getValue("TYPZ","doctrans");
		String sql="select t.le, nvl(t1.numb,0)numb from (" +
				"    select '01' le from dual" +
				"    union all" +
				"     select '02' from dual" +
				"      union all" +
				"     select '03' from dual) t left join  (select AUDIT_TYPE le,count(1) numb from "+doctrans+".TZ_APPLY_PROJECT_INFO t where 1=1 [:year|and to_char(apply_date,'yyyy')=:year]" +
				"[:cityCode| and substr(place_code,0,4)||'00'=:cityCode] group by AUDIT_TYPE) t1 on t.le=t1.le  order by  t.le" ;
		QueryAndNamedParams params = QueryUtils.translateQuery(sql, searchColumn);
		JSONArray jsonArray=messageInfoMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
		sql="select nvl(sum(TOTAL_MONEY)/10000,0) ta, nvl(sum(EQUITY_FUND)/10000,0) zy,nvl(sum (GOV_INVEST_FUND)/10000,0) zf,nvl(sum(BANK_LOAN_FUND)/10000,0) yh,nvl(sum(OTHER_FUND)/10000,0) qt from "+doctrans+".TZ_APPLY_PROJECT_INFO where 1=1 [:year|and to_char(apply_date,'yyyy')=:year]" +
				"[:cityCode| and substr(place_code,0,4)||'00'=:cityCode]";
		params = QueryUtils.translateQuery(sql, searchColumn);
		JSONArray total=messageInfoMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("xmnum",jsonArray);
		jsonObject.put("total",total);
		JsonResultUtils.writeSingleDataJson(jsonObject, response);
	}
	/**
	 *
	 * 功能描述: 查看之后重新获取首页消息条数
	 *
	 * @param:
	 * @return:
	 * @auther: 皇甫壮
	 * @date: 2018-10-25 10:02
	 */
	@RequestMapping(value = "/messageNum", method = RequestMethod.GET)
	public void messageNum(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
			Map<String, Object> filterMapItem = new HashMap<>();
			filterMapItem.put("dataType", "1");
			filterMapItem.put("ifread","1");
			filterMapItem.put("userCode",getLoginUserCode(request));
			String sql=" select count(1) cnum,'1' from t_message_info where 1=1 [:dataType| and dataType=:dataType][:ifread| and nvl(ifread,'1')=:ifread][:userCode| and user_Code=:userCode]";
			QueryAndNamedParams params = QueryUtils.translateQuery(sql, filterMapItem);
			JSONArray jsonArray=todoItemMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),pageDesc);
            if(jsonArray!=null&&jsonArray.size()>0){
				JsonResultUtils.writeSingleDataJson(jsonArray.getJSONObject(0).get("cnum"), response);
			}
	}
	
	
	/**
	 *
	 * 获取首页公示信息
	 */
	@RequestMapping(value = "/getTsjbdj", method = RequestMethod.GET)
	public void getTsjbdj(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
			Map<String, Object> filterMapItem = new HashMap<>();
			String sql="select REC_ID,TS_TITLE,TS_CLSTATUS,INS_TIME ,TS_PHONENO,FLOWINSTID from TSJBXT.T_TSJBDJB  WHERE TS_CLSTATUS = '01' ORDER BY EDIT_TIME DESC";
			QueryAndNamedParams params = QueryUtils.translateQuery(sql, filterMapItem);
			JSONArray jsonArray=todoItemMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),pageDesc);
           if(jsonArray!=null&&jsonArray.size()>0){
				JsonResultUtils.writeSingleDataJson(jsonArray, response);
			}
	}
	
	/**
	 *
	 * 获取首页投诉事项分布数据
	 */
	@RequestMapping(value = "/getTsjbdjType", method = RequestMethod.GET)
	public void getTsjbdjType(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
			Map<String, Object> filterMapItem = new HashMap<>();
			String sql="SELECT s.TS_NAME as name,count(t.SX_TYPE) AS value FROM TSJBXT.T_TSJBDJB t LEFT JOIN TSJBXT.T_TSSX_BM s ON t.SX_TYPE = s.REC_ID GROUP BY s.TS_NAME";
			QueryAndNamedParams params = QueryUtils.translateQuery(sql, filterMapItem);
			JSONArray jsonArray=todoItemMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),pageDesc);
			/*for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				if (StringUtils.isNotEmpty(jsonObject.getString("name"))) {
					jsonObject.put("name", CodeRepositoryUtil.getValue("YSSXLX", jsonObject.getString("name")));
				}
				
			}*/
          if(jsonArray!=null&&jsonArray.size()>0){
				JsonResultUtils.writeSingleDataJson(jsonArray, response);
			}
	}
	
	
	/**
	 *获取满意度调查覆盖数据
	 */
	@RequestMapping(value = "/getMuddType", method = RequestMethod.GET)
	public void getMuddType(HttpServletRequest request,PageDesc pageDesc, HttpServletResponse response) {
			Map<String, Object> filterMapItem = new HashMap<>();
			String sql="SELECT CITY as city,count(REC_ID) AS num FROM MYDDCXT.T_QUESTION_ANS GROUP BY CITY";
			QueryAndNamedParams params = QueryUtils.translateQuery(sql, filterMapItem);
			JSONArray jsonArray=todoItemMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),pageDesc);
			if(jsonArray!=null&&jsonArray.size()>0){
				JsonResultUtils.writeSingleDataJson(jsonArray, response);
			}
	}

}
